package com.shangyitong.yygh_cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shangyitong.ResultCodeEnum;
import com.shangyitong.exception.HospitalException;
import com.shangyitong.yygh.model.cmn.Dict;
import com.shangyitong.yygh.vo.cmn.DictEeVo;
import com.shangyitong.yygh_cmn.listener.DictListener;
import com.shangyitong.yygh_cmn.mapper.DictMapper;
import com.shangyitong.yygh_cmn.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        List<Dict> childData = baseMapper.findChildData(id);
        for (Dict dict : childData) {
            Long dictId = dict.getId();
            boolean hasChildren = isChildren(dictId);
            dict.setHasChildren(hasChildren);
        }
        return childData;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //设置下载信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = "dict";
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //查询数据库
            List<Dict> dicts = baseMapper.selectList(null);
            List<DictEeVo> dictEeVos = new ArrayList<>();
            for (Dict dict : dicts) {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict, dictEeVo);
                dictEeVos.add(dictEeVo);
            }
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict").doWrite(dictEeVos);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper))
                    .sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getName(String dictCode, String value) {
        if (StringUtils.isEmpty(dictCode)) {
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value",value));
            if (dict == null) {
                throw new HospitalException(ResultCodeEnum.SERVICE_ERROR);
            }
            return dict.getName();
        }
        Dict dict = baseMapper.getByDictcode(dictCode);
        if (dict == null) {
            throw new HospitalException(ResultCodeEnum.DATA_ISNULL);
        }
        Long dictId = dict.getId();
        Dict one = baseMapper.selectOne(new QueryWrapper<Dict>()
                .eq("parent_id", dictId)
                .eq("value", value));
        if (one == null) {
            throw new HospitalException(ResultCodeEnum.SERVICE_ERROR);
        }
        return one.getName();
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>()
                .eq("dict_code", dictCode));
        Long dictId = dict.getId();
        return baseMapper.selectList(new QueryWrapper<Dict>()
                .eq("parent_id", dictId));
    }

    //判断是否有子数据
    private boolean isChildren(Long id) {
        Integer isCount = baseMapper.getIsCount(id);
        return isCount > 0;
    }
}
